## ---------------------------------------
# Calculate instrument
## ---------------------------------------

constructIV <- function(df){
  df[, weight := .N, by = c("uniqueid")]
  df[, i_resid := mean(pti, na.rm = T), by = c("uniqueid", "judge_cat", "court_time1", "totOGS2")]
  df[, i_obs := .N, by = c("uniqueid", "judge_cat", "court_time1", "totOGS2")]
  df[, tmp_mean := mean(pti, na.rm = T), by = c("judge_cat", "court_time1", "totOGS2")]
  df[, tmp_obs := .N, by = c("judge_cat", "court_time1", "totOGS2")]
  df[, judgeiv := (tmp_mean * tmp_obs - (i_obs * i_resid)) / (tmp_obs - i_obs)]
  df$tmp_mean <- df$tmp_obs <- df$i_resid <- df$i_obs <- NULL
  return(df)
}

